package com.gz.furnitures.web;

import com.gz.furnitures.entity.Furn;
import com.gz.furnitures.entity.Page;
import com.gz.furnitures.service.impl.FurnServiceImpl;
import com.gz.furnitures.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/customFurnServlet")
public class CustomFurnServlet extends BasicServlet {
    FurnServiceImpl furnService = new FurnServiceImpl();

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置分页
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo, pageSize);
        request.setAttribute("page", page);
        request.getRequestDispatcher("/views/custom/index.jsp").forward(request, response);
    }

    protected void pageByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        //注意
        //(1)这里如果有参数name,但没有值，如name=
        //则返回所有的家具，即相当于% %
        //(2)而如果没有参数name,则相当于name=null,不返回数据，即0个家具
        String name = request.getParameter("name");
        //故下面做修改,将null和""业务逻辑合并在一起
        if (name == null) {
            name = "";
        }
        Page<Furn> page = furnService.pageByName(pageNo, pageSize, name);
        StringBuilder url = new StringBuilder("customFurnServlet?action=pageByName");
        if(!"".equals(name)) {
            url.append("&name=").append(name);
        }
        page.setUrl(url.toString());
        request.setAttribute("page", page);
        request.getRequestDispatcher("/views/custom/index.jsp").forward(request, response);
    }
}
